package com.service.screenReception.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.utils.RedisUtil;
import com.service.screenReception.dao.DeviceDao;
import com.service.screenReception.dao.SiteDao;
import com.service.screenReception.dao.TerminalUserListDao;
import com.service.screenReception.dto.AppUserInfoDto;
import com.service.screenReception.dto.DeviceDto;
import com.service.screenReception.dto.DeviceInfoDto;
import com.service.screenReception.dto.SiteInfoDto;
import com.service.screenReception.entity.DeviceInfo;
import com.service.screenReception.entity.SiteInfo;
import com.service.screenReception.service.DemoService;
import com.service.screenReception.task.CloudCampusApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.service.config.constant.ApiUrlConstants;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service("demoService")
@Slf4j
public class DemoServiceImpl implements DemoService,ApiUrlConstants{
    @Resource
    private SiteDao siteDao;
    @Resource
    private DeviceDao deviceDao;
    @Resource
    private TerminalUserListDao terminalUserListDao;
    @Resource
    RestTemplate restTemplate;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private CloudCampusApi cloudCampusApi;

    @Override
    public List<SiteInfoDto> getSitesInfo(String userName, String password) {
        HttpHeaders requestHeaders = this.getHeader(userName,password);

        //获取站点
        boolean flag = true;
        int pageIndex = 1;
        List<SiteInfoDto> siteInfoDtos = new ArrayList<>();

        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://naas.huaweicloud.com:18002/controller/campus/v3/sites?pageSize=100&pageIndex=" + pageIndex, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = response.getBody().getJSONArray("data");
                if (!data.isEmpty()) {
                    siteInfoDtos.addAll(data.toJavaList(SiteInfoDto.class));
                    pageIndex++;
                } else {
                    flag = false;
                }
                List<DeviceInfoDto> siteDevices = this.getSiteDevices(userName, password, "");
                for (SiteInfoDto siteInfoDto : siteInfoDtos) {
                    List<DeviceInfoDto> list=new ArrayList();
                    for (DeviceInfoDto deviceInfoDto:siteDevices)
                    {
                        if(deviceInfoDto.getSiteId().equals(siteInfoDto.getId()))
                        {
                            list.add(deviceInfoDto);
                        }
                    }
                    siteInfoDto.setDevices(list);
                }
                redisUtil.setList(siteInfoDtos.get(0).getId().concat("_siteData"),siteInfoDtos);

                //查询数据库
                List<SiteInfo> allSites = siteDao.findAllSites();
                if (allSites.size()==0)
                {
                    for (SiteInfoDto info : siteInfoDtos) {
                        siteDao.insert(info);
                    }
                }
                if (allSites.size()>0){
                    for (SiteInfoDto info:siteInfoDtos) {
                        if(!allSites.toString().contains(info.getId()))
                        {
                            //insert
                            siteDao.insert(info);
                        }
                        for(SiteInfo site : allSites)
                        {
                            if(site.getId().equals(info.getId()) && !site.toString().equals(info.toString()))
                            {
                                //delete
                                siteDao.deleteById(info.getId());
                                //insert
                                siteDao.insert(info);
                            }
                        }
                    }
                }
                return siteInfoDtos;
             }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("debug getSites ==>" + e.getMessage());
                return null;
            }
        return null;
    }

    @Override
    public List<DeviceInfoDto> getSiteDevices(String userName, String password, String siteId) {
        HttpHeaders requestHeaders = this.getHeader(userName, password);
        //获取站点
        boolean flag = true;
        int pageIndex = 1;
        List<DeviceInfoDto> deviceInfoDtos = new ArrayList<>();
        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://naas"+DEVICES_URL+"?pageSize=100&pageIndex=" + pageIndex+ "&siteId=" + siteId, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = response.getBody().getJSONArray("data");
                if (!data.isEmpty()) {
                    deviceInfoDtos.addAll(data.toJavaList(DeviceInfoDto.class));
                    pageIndex++;
                } else {
                    flag = false;
                }
                redisUtil.setList(deviceInfoDtos.get(0).getId().concat("_deviceData"),deviceInfoDtos);

                //查询数据库
                List<DeviceInfo> allDevices = deviceDao.findAllDevices();
                if (allDevices.size()==0)
                {
                    for (DeviceInfoDto info : deviceInfoDtos) {
                        deviceDao.insert(info);
                    }
                }
                if (allDevices.size()>0){
                    for (DeviceInfoDto info:deviceInfoDtos) {
                        if(!allDevices.toString().contains(info.getId()))
                        {
                            //insert
                            deviceDao.insert(info);
                        }
                        for(DeviceInfo device : allDevices)
                        {
                            if(device.getId().equals(info.getId()) && !device.toString().equals(info.toString()))
                            {
                                //delete
                                deviceDao.deleteById(info.getId());
                                //update
                                deviceDao.insert(info);
                            }
                        }
                    }
                }
                return deviceInfoDtos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("debug getDevices ==>" + e.getMessage());
            return null;
        }
        return null;
    }

    @Override
    public List<AppUserInfoDto> getUserOnlineTime(String userName, String password) {
        List<SiteInfoDto> sites = this.getSitesInfo(userName, password);
        HttpHeaders requestHeaders = this.getHeader(userName, password);

        List<AppUserInfoDto> userInfoDtos=new ArrayList<>();
        sites.forEach(site->{
            HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.exchange("https://naas.huaweicloud.com:18002/controller/campus/v1/performanceservice/station/online/statistic/" +site.getId(), HttpMethod.GET, requestEntity, JSONObject.class);
            AppUserInfoDto data = response.getBody().getObject("data", AppUserInfoDto.class);
            data.setSiteId(site.getId());
            userInfoDtos.add(data);
        });
        redisUtil.setList("userOnlineTime",userInfoDtos);

        List<AppUserInfoDto> all = terminalUserListDao.findAll();
        if (all.size()==0)
        {
            for (AppUserInfoDto userInfoDto : userInfoDtos) {
                int i = terminalUserListDao.insertUserOnlineTime(userInfoDto);
            }
        }else {
            for (AppUserInfoDto info:userInfoDtos) {
                if(!all.toString().contains(info.getSiteId()))
                {
                    //insert
                    terminalUserListDao.insertUserOnlineTime(info);
                }
                for(AppUserInfoDto device : all)
                {
                    if(device.getSiteId().equals(info.getSiteId()) && !device.toString().equals(info.toString()))
                    {
                        //delete
                        terminalUserListDao.deleteById(info.getSiteId());
                        //insert
                        terminalUserListDao.insertUserOnlineTime(info);
                    }
                }
            }
        }
        return userInfoDtos;
    }



    public HttpHeaders getHeader(String userName,String password)
    {
        HttpHeaders requestHeaders = new HttpHeaders();
        String token="";
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());

        try {
            if (redisUtil.exist(userName.concat("token"))) {
                token = redisUtil.getValue(userName.concat("token"));
            } else {
                //获取token
                token = cloudCampusApi.getToken(userName, password, requestHeaders, "naas");
                redisUtil.set(userName.concat("token"), 1, token, 10);
            }
            //获取站点
            requestHeaders.add("X-AUTH-TOKEN", token);
        } catch (Exception e) {
            log.error("token Access failure!");
        }
        return requestHeaders;
    }
}
